package de.gwtprime.server;

import java.util.HashSet;
import java.util.Set;

import org.apache.log4j.Logger;

import com.google.appengine.api.channel.ChannelMessage;
import com.google.appengine.api.channel.ChannelService;
import com.google.appengine.api.channel.ChannelServiceFactory;

import de.gwtprime.server.model.User2;

/**
 * Create new channels and push messages to the client
 * @author jan
 *
 */
public class ChannelManager {
	
	/**
	 * Logger
	 */
	private static Logger logger = Logger.getLogger(ChannelManager.class);

	static Set<String> connectedClients = new HashSet<>();
	
	public static void pushToClient(User2 user, String message){
		pushToClient(user.getId().toString(), message);
	}
	
	/**
	 * Send the given message to the given user ID
	 * @param key
	 * @param message
	 */
	public static void pushToClient(String key, String message){
		ChannelService channelService = ChannelServiceFactory.getChannelService();
		
		try {
			channelService.sendMessage(new ChannelMessage(key, message));
		} catch (Exception e) {
			logger.debug(String.format("Could not send message '%s' to key '%s'", message, key));
		}
		
		
	}
	
	/**
	 * Get a new channel token for the given user ID
	 * @param userId
	 * @return
	 */
	public static String getChannelTokenForUser(Long userId){
		
		if(userId == null)
			throw new IllegalArgumentException("Can't generate channel token! Given userId was 'null'");

		// Generate a unique channel token, based on the given user id
	    ChannelService channelService = ChannelServiceFactory.getChannelService();
	    String token = channelService.createChannel(userId.toString());
	    
	    connectedClients.add(token);
	    return token;
	}
	
	/**
	 * Push message to all clients
	 * @param message
	 */
	public static void pushToAllClients(String message){
		for(String key : connectedClients){
			pushToClient(key, message);
		}
	}
	
}
